package net.java.mediasystems.database.core.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import net.java.mediasystems.database.core.model.MetadataValue;
import net.java.mediasystems.database.core.model.StorageContainer;
import net.java.mediasystems.database.core.repository.jpa.MetadataValueRepository;
import net.java.mediasystems.database.core.repository.jpa.StorageContainerRepository;
import net.java.mediasystems.database.core.service.StorageContainerService;

/**
 * StorageContainerService Implementation.
 */
public class StorageContainerServiceImpl implements StorageContainerService {

	private static final Logger LOG = LoggerFactory.getLogger(StorageContainerServiceImpl.class);
	
	private StorageContainerRepository storageContainerRepository;
	private MetadataValueRepository metadataValueRepository;
	
	/**
	 * {@inheritDoc}
	 */
	@Transactional
	@Override
	public StorageContainer addStorageContainer(StorageContainer storageContainer) {
		Assert.notNull(storageContainer);
		
		LOG.debug("Adding a new Storage-Container.");
		this.storageContainerRepository.save(storageContainer);
		
		if (CollectionUtils.isNotEmpty(storageContainer.getMetadataValues())) {
			LOG.debug("Adding the Metadata to the newly created Storage-Container.");
			
			for (MetadataValue curMetadataValue : storageContainer.getMetadataValues()) {
				curMetadataValue.setStorageContainer(storageContainer);
				this.metadataValueRepository.save(curMetadataValue);
			}
		}
		
		return storageContainer;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Transactional(readOnly = true)
	@Override
	public List<StorageContainer> getAllStorageContainers() {
		return this.storageContainerRepository.findAll();
	}

	public void setStorageContainerRepository(
			StorageContainerRepository storageContainerRepository) {
		this.storageContainerRepository = storageContainerRepository;
	}

	public void setMetadataValueRepository(
			MetadataValueRepository metadataValueRepository) {
		this.metadataValueRepository = metadataValueRepository;
	}
}
